package com.td.framework.webmanager.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenticationFilter implements Filter {//一定要使用Filter接口 
	private FilterConfig filterConfig; 

	private String onErrorUrl; 

	public void init(FilterConfig config) throws ServletException {
	filterConfig = config; 
	onErrorUrl = filterConfig.getInitParameter("onError"); 
	if (onErrorUrl == null || "".equals(onErrorUrl)) { 
	onErrorUrl = "onError"; 
	} 
	} 

	public void doFilter(ServletRequest request, ServletResponse response, 
	FilterChain next) throws IOException, ServletException { 
	HttpServletRequest httpRequest = (HttpServletRequest) request; 
	HttpServletResponse httpResponse = (HttpServletResponse) response; 
	HttpSession httpSession = httpRequest.getSession(); 
	/** 
	* @ 页面缓存设定 
	* <br>确保浏览器不缓存页面数据 
	*/ 

	httpResponse.setHeader("Cache-Control","no-cache"); 
	httpResponse.setHeader("Cache-Control","no-store"); 
	httpResponse.setDateHeader("Expires", 0); 
	httpResponse.setHeader("Pragma","no-cache"); 

	/** 
	* @ 过滤未登录用户无效请求 
	* <br>未登录用户请求跳转到/login.jsp 
	*/ 
	if (httpSession.getAttribute("userinfo") == null) {
		response.setCharacterEncoding("utf-8");  
		response.setContentType("text/html; charset=utf-8"); 
		PrintWriter pw = response.getWriter(); 
	pw.println("<script type='text/javascript'>");
	pw.println("alert('请重新登录!');");
	httpSession.invalidate();
	pw.println("window.parent.location.href='"+onErrorUrl+"';");
	pw.println("</script>");
	//httpRequest.getRequestDispatcher(onErrorUrl).forward(httpRequest, 
	//httpResponse); 	
	} else {
	next.doFilter(request, response);
	}
	} 
	public void destroy() { 
	}

	} 